////////////////////////////////////////////////////////////////////////////////
// Copyright 2006 CORE Solutions Limited
// All rights reserved.
// PROPRIETARY AND CONFIDENTIAL INFORMATION.
// Use is subject to license terms.
//
// FUNCTION ID      :   CustomIterateTag.java
// AUTHOR           :   ric.yik
// DATE CREATE      :   2006/6/22
// DESCRIPTION      :
//                  :
//                  :
//                  :
//
// MODIFICATION HISTORY:
// DATE         AUTHOR          VERSION NO.         COMMENT
// -----------  --------------  ------------------  -------------------
// 2006/06/22   Ric Yik         1.0                 BugZilla #5535
//
//
//
////////////////////////////////////////////////////////////////////////////////

package com.erp.framework.controller.taglib;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

import javax.servlet.jsp.JspException;

import org.apache.struts.taglib.html.Constants;
import org.apache.struts.util.BeanUtils;
import org.apache.struts.util.ResponseUtils;

import com.erp.app.common.ProjectConstants;
import com.erp.framework.SimpleConstants;
import com.erp.framework.controller.form.ButtonUIControl;
import com.erp.framework.controller.form.MultiRow;
import com.erp.framework.controller.form.SimpleCoreForm;
import com.erp.framework.controller.form.SimpleMaintStyleForm;
import com.erp.framework.controller.form.UIControlInterceptor;
import com.erp.framework.util.BeanUtil;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;
import com.erp.framework.util.mainmenu.MenuObject;

public class CustomButtonTag extends javax.servlet.jsp.tagext.TagSupport implements ButtonUIControl {

    private boolean useExtensions = false;

    private String uiType = SimpleConstants.UI_TYPE_BUTTON;

    private String form = null;
    private String pageEvent = "";
    private String value = null;
    private String onClick = null;
    private String styleClass = null;
    private String name = null;
    private String property = null;
    private boolean allowDeselectField = true;
    private boolean useNestedProperty = false;
	private String disabled = null;
	private String pageEventSrc = null;
    private String actionIdx = null;

    private String visibility = SimpleConstants.UI_VISIBILITY_EDITABLE;

    private String multiRow = null;

    private boolean deleteButton = false;

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getDeleteButton()
     */
    public boolean getDeleteButton() {
        return deleteButton;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setDeleteButton(boolean)
     */
    public void setDeleteButton(boolean deleteButton) {
        this.deleteButton = deleteButton;
        this.setUseExtensions(true);
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setForm(java.lang.String)
     */
    public void setForm(String form) {
        this.form = form;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setPageEvent(java.lang.String)
     */
    public void setPageEvent(String pageEvent) {
        this.pageEvent = pageEvent;
    }

	/**
     * @see com.erp.framework.controller.form.ButtonUIControl#setPageEventSrc(java.lang.String)
     */
	public void setPageEventSrc(String pageEventSrc) {
        this.pageEventSrc = pageEventSrc;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setValue(java.lang.String)
     */
    public void setValue(String value) {
        this.value = value;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setName(java.lang.String)
     */
    public void setName(String name) {
        this.name = name;
    }

	 /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setDisabled(java.lang.String)
     */
	public void setDisabled(String disabled) {
        this.disabled = disabled;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setOnClick(java.lang.String)
     */
    public void setOnClick(String onClick) {
        this.onClick = onClick;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setStyleClass(java.lang.String)
     */
    public void setStyleClass(String styleClass) {
        this.styleClass = styleClass;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getDisabled()
     */
    public String getDisabled() {
        return disabled;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getForm()
     */
    public String getForm() {
        return form;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getName()
     */
    public String getName() {
        return name;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getOnClick()
     */
    public String getOnClick() {
        return onClick;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getPageEvent()
     */
    public String getPageEvent() {
        return pageEvent;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getPageEventSrc()
     */
    public String getPageEventSrc() {
        return pageEventSrc;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getStyleClass()
     */
    public String getStyleClass() {
        return styleClass;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getValue()
     */
    public String getValue() {
        return value;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#isTab()
     */
    public boolean isTab() {
        return SimpleConstants.UI_TYPE_TAB.equalsIgnoreCase(this.getUiType());
    }

    public boolean isSelectField() {
        return SimpleConstants.UI_TYPE_SELECT_FIELD.equalsIgnoreCase(this.getUiType());
    }

    public boolean isDisplayOnly() {
        return SimpleConstants.UI_VISIBILITY_DISPLAYONLY.equals(this.getVisibility());
    }

    public boolean isHidden() {
        return SimpleConstants.UI_VISIBILITY_HIDDEN.equals(this.getVisibility());
    }

    public boolean isNavigator() {
    	return SimpleConstants.UI_TYPE_NAVIGATOR.equals(this.getUiType());
    }

    public int doEndTag() throws JspException {

        StringBuffer rslt = new StringBuffer();
        try {
            rslt = new StringBuffer();
            int scope = pageContext.getAttributesScope(form);
            SimpleCoreForm userForm = (SimpleCoreForm) pageContext.getAttribute(form, scope);

            if (userForm == null)
                return EVAL_PAGE;

            ArrayList menuObjectList = userForm.getMenuObjectList();

            Logger.all(this, "doEndTag(), menuObjectList.size()=" + menuObjectList.size());
            if(!this.isNavigator()){
            	 for (int i = 0; menuObjectList != null && i < menuObjectList.size(); i++) {
                     MenuObject obj = (MenuObject) menuObjectList.get(i);

                     if (obj == null)
                         continue;

                     if (!pageEvent.equals(obj.getObjectAction()))
                         continue;
                     if (!"button".equalsIgnoreCase(obj.getObjectType()))
                         continue;
                     if (!ProjectConstants.GENERIC_YES.equalsIgnoreCase(obj.getVisibleDisplay()))
                         continue;

                     String buttonValue = (value == null) ? obj.getName() : value;

         			String disabledValue = (disabled == null) ? obj.getName() : disabled;
         			String disabledHtml = ("true".equalsIgnoreCase(disabledValue)) ? "disabled" : "";

     				//this is for db acccess disabled value only
                     String disabled = (ProjectConstants.GENERIC_YES.equalsIgnoreCase(obj.getEnableDisplay())) ? "" : "disabled";

                     if (userForm instanceof UIControlInterceptor) {
                         ((UIControlInterceptor) userForm).beforeRenderButton(this);
                     }

                     if (this.isTab()) {
                         if (!(userForm instanceof SimpleMaintStyleForm)) throw new JspException("FormBean is not a MaintStyle Form");
                         String current = (((SimpleMaintStyleForm) userForm).getFolderIdx().equals(String.valueOf(this.getPageEventSrc()))) ? " id = \"current\"" : "";
                         rslt.append("<li").append(current).append(">");
                         if (!this.isDisplayOnly()) rslt.append("<a href=\"javascript:doSubmit('changeFolder', '").append(this.getPageEventSrc()).append("');\">");
                         rslt.append("<span>").append(buttonValue).append("</span>");
                         if (!this.isDisplayOnly()) rslt.append("</a>");
                         rslt.append("</li>");
                     } else {
                         boolean renderButton = !this.isHidden();
                         if (this.isDisplayOnly()) disabled = "disabled";
                         if (this.getUseExtensions() && renderButton) {
                             if (this.getDeleteButton()) {
                                 if (CommonUtil.isEmpty(this.getMultiRow())) {
                                     throw new JspException("The attribute \"multiRow\" is required if \"deleteButton\" is true.");
                                 }
                                 Object object = pageContext.findAttribute(this.getMultiRow());
                                 if (object == null) {
                                     throw new JspException("MultiRow " + this.getMultiRow() + " not found form the pageContext.");
                                 }
                                 if (!(object instanceof MultiRow)) {
                                     throw new JspException(this.getMultiRow() + " is not a MultiRow.");
                                 }
                                 MultiRow row = (MultiRow) object;
                                 if (row.isDeleted()) {
                                     rslt.append("<img src=\"images/deleted.gif\" width=\"15\" height=\"15\" border=\"0\">\n");
                                     if (!this.getUseNestedProperty()) {
                                         rslt.append("<input type=\"hidden\" name=\"isDelete\" value=\"").append(row.getIdx()).append("\" />\n");
                                     }
                                     renderButton = false;
                                 }
                             }
                         }
                         if (renderButton) {
                             if (CommonUtil.isEmpty(this.getStyleClass())) {
                                 this.setStyleClass("button1");
                             }
         					rslt.append("<input type=\"button\" value=\"" + buttonValue + "\" " + disabled + " " + disabledHtml);
                             if ((styleClass != null) && (!styleClass.trim().equals(""))) {
                                 rslt.append(" class=\"" + styleClass + "\"");
                             }

                             String buttonName = (name == null) ? obj.getName() : name;
                             if (buttonName != null) {
                                 if (!"".equals(buttonName)) {
                                     rslt.append(" name=\"" + buttonName + "\"");
                                 }
                             }

                             if (("".equals(disabled))) {
                                 if ((onClick != null) && (!onClick.trim().equals(""))) {
                                     rslt.append(" onclick=\"" + onClick + "\"");
                                 } else {
                                     rslt.append(" onclick=\"javascript:");
                                     if ((actionIdx != null) && (!actionIdx.trim().equals(""))) {
                                         rslt.append("document.forms[0].actionIdx.value = '").append(actionIdx).append("';");
                                     }
             						if((pageEventSrc != null) && (!pageEventSrc.trim().equals(""))) {
                                         rslt.append("doSubmit('" + pageEvent + "', '" + pageEventSrc + "');");
             						} else {
             							rslt.append("doSubmit('" + pageEvent + "');");
             						}
                                     rslt.append("\"");
                                 }
                             }

                             rslt.append(">");
                         }
                     }

                     Logger.all(this, "doEndTag(), html=" + rslt.toString());
                     pageContext.getOut().print(rslt.toString());
                 }
            }else{
            	int totalPage=userForm.getTotalPage();

            	if(totalPage==0){
            		rslt.append("&nbsp;");
            	}else {
            		 Object form = pageContext.findAttribute(Constants.BEAN_KEY);
                     if (form == null) {
                         Logger.debug(this, "form is null.");
                         return SKIP_BODY;
                     }
            		String value = CommonUtil.nullToString(BeanUtil.getPropertyDefault(form, "scrollTo"));

            		rslt.append("<input type=\"button\" value=\"Go\" class=\"button1\" onClick=\"javascript:doSubmit('scrollTo');\" >");
            		rslt.append("\n");
            		rslt.append("Page");
            		rslt.append("\n");
            		//rslt.append("<html:text property=\"scrollTo\" styleClass=\"textbox1\" readonly=\"<%=rowReadOnly%>\" maxlength=\"4\" size=\"4\" value=\"<%=String.valueOf(factSearchForm.getCurrentPage())%>\"/>");
            		rslt.append("<input type=\"text\" name=\"scrollTo\" maxlength=\"4\" size=\"4\" value=\""+userForm.getCurrentPage()+"\" class=\"textbox1\">");
            		rslt.append("of\t");
            		rslt.append(userForm.getTotalPage());
            	}

            	rslt.append("<input type=\"button\" value=\"|&lt;&lt;\" class=\"button1\" onClick=\"javascript:doSubmit('"+userForm.ACTION_SCROLL_TO_FIRST_PAGE+"');\"  "+((userForm.getSidx()==0)?"disabled" : "")+">");
            	rslt.append("<input type=\"button\" value=\"&lt;&lt;\" class=\"button1\" onClick=\"javascript:doSubmit('"+userForm.ACTION_SCROLL_LEFT+"');\" "+((userForm.getSidx()==0)?" disabled" : "")+">");
            	rslt.append("<input type=\"button\" value=\"&gt;&gt;\" class=\"button1\" onClick=\"javascript:doSubmit('"+userForm.ACTION_SCROLL_RIGHT+"');\" "+((userForm.getSidx()<Integer.parseInt(userForm.getLastPageSidx()))?"":"disabled" )+">");
            	rslt.append("<input type=\"button\" value=\"&gt;&gt|\" class=\"button1\" onClick=\"javascript:doSubmit('"+userForm.ACTION_SCROLL_TO_LAST_PAGE+"');\" "+((userForm.getSidx()<Integer.parseInt(userForm.getLastPageSidx()))?"":"disabled" )+">");
            	Logger.all(this, "doEndTag(), html=" + rslt.toString());
                pageContext.getOut().print(rslt.toString());
            }

        } catch (Exception e) {
            Logger.logExceptions(this, e);
            Logger.sql("doEndTag(), html=" + rslt.toString());
        }

        this.reset();
        return EVAL_PAGE;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getUseExtensions()
     */
    public boolean getUseExtensions() {
        return useExtensions;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setUseExtensions(boolean)
     */
    public void setUseExtensions(boolean useExtensions) {
        this.useExtensions = useExtensions;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getUiType()
     */
    public String getUiType() {
        return uiType;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setUiType(java.lang.String)
     */
    public void setUiType(String uiType) {
        this.uiType = uiType;
        this.setUseExtensions(true);
    }

    public void reset() {
        form = null;
        pageEvent = "";
        value = null;
        onClick = null;
        styleClass = null;
        name = null;
        disabled = null;
        pageEventSrc = null;
        actionIdx = null;
        multiRow = null;
        deleteButton = false;
        uiType = SimpleConstants.UI_TYPE_BUTTON;
        visibility = SimpleConstants.UI_VISIBILITY_EDITABLE;
        property = null;
        allowDeselectField = true;
        useNestedProperty = false;
    }

    public void release() {
        this.reset();
        super.release();
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getMultiRow()
     */
    public String getMultiRow() {
        return multiRow;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setMultiRow(java.lang.String)
     */
    public void setMultiRow(String multiRow) {
        this.multiRow = multiRow;
        this.setUseExtensions(true);
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#getVisibility()
     */
    public String getVisibility() {
        return visibility;
    }

    /**
     * @see com.erp.framework.controller.form.ButtonUIControl#setVisibility(java.lang.String)
     */
    public void setVisibility(String visibility) {
        this.visibility = visibility;
        this.setUseExtensions(true);
    }

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }

    public boolean getAllowDeselectField() {
        return allowDeselectField;
    }

    public void setAllowDeselectField(boolean allowDeselect) {
        this.allowDeselectField = allowDeselect;
    }

    public String getActionIdx() {
        return actionIdx;
    }

    public void setActionIdx(String actionIdx) {
        this.actionIdx = actionIdx;
    }

    public boolean getUseNestedProperty() {
        return useNestedProperty;
    }

    public void setUseNestedProperty(boolean useNestedProperty) {
        this.useNestedProperty = useNestedProperty;
    }

    public boolean isFieldSelected() {
        if (!this.isSelectField()) return false;
        try {
            String beanName = CommonUtil.getString(this.getMultiRow(), this.getForm());
            if (CommonUtil.isEmpty(beanName)) return false;
            Object formOrMultiRow = pageContext.findAttribute(beanName);
            return !CommonUtil.isEmpty(BeanUtil.getPropertyDefault(formOrMultiRow, this.getProperty()));
        } catch (RuntimeException e) {
            Logger.logExceptions(this, e);
            return false;
        }
    }

}